import pyttsx3
from concurrent.futures import ThreadPoolExecutor


def example():
    #   创建对象
    engine = pyttsx3.init()
    # 获取当前语音速率
    rate = engine.getProperty('rate')

    print(f'语音速率：{rate}')
    # 设置新的语音速率

    engine.setProperty('rate', 200)

    # 获取当前语音音量
    volume = engine.getProperty('volume')

    print(f'语音音量：{volume}')

    # 设置新的语音音量，音量最小为 0，最大为 1
    engine.setProperty('volume', 1.0)

    # 获取当前语音声音的详细信息
    voices = engine.getProperty('voices')
    print(f'语音声音详细信息：{voices}')

    # 设置当前语音声音为女性，当前声音不能读中文
    # engine.setProperty('voice', voices[1].id)

    # 设置当前语音声音为男性，当前声音可以读中文
    engine.setProperty('voice', voices[0].id)

    # 获取当前语音声音
    voice = engine.getProperty('voice')

    print(f'语音声音：{voice}')

    engine.say("hello world")
    engine.say('你好，世界')

    # FIXME 等待语音播报完毕，否则听不到播报声音
    engine.runAndWait()

    # 读txt文档
    # with open(r"文档地址.txt","r",encoding="utf-8") as f:
    # engine.say(f.line())


class VoiceSpeaker:
    def __init__(self):
        self.engine = pyttsx3.init()
        self.engine.setProperty('rate', 150)
        self.engine.setProperty('volume', 1.0)
        self.voices = self.engine.getProperty('voices')
        print(f'语音声音详细信息：{self.voices}')
        self.engine.setProperty('voice', self.voices[0].id)
        self.pool = ThreadPoolExecutor(
            max_workers=1, thread_name_prefix='VoiceSpeaker')

    def say(self, msg):
        # 单开一个线程专门用来播放语音
        def _say():
            self.engine.say(msg)
            self.engine.runAndWait()

        self.pool.submit(_say)


VoicePlayer = VoiceSpeaker()


def main():
    vs = VoiceSpeaker()
    vs.say('测试100项功能，合格100项，不合格0项')


if __name__ == '__main__':
    main()
